package com.easy.leetcode.backTracking;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName GenerateParenthesis22
 * @Description TODO
 * @Author zheng
 * @Date 2021/12/7 15:22
 * @Version 1.0
 **/
public class GenerateParenthesis22 {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        Deque<String> path = new ArrayDeque<String>();
        backTracking(n, 0, 0, path, res);
        return res;
    }

    public void backTracking(int n, int left, int right, Deque<String> path, List<String> res) {
        //退出条件
        if (path.size() == n * 2) {
            res.add(String.join("", path));
            return;
        }
        //左括号个数小于n,一直加
        if (left < n) {
            path.add("(");
            backTracking(n, left + 1, right, path, res);
            path.removeLast();
        }
        //右括号个数少于左括号一直加
        if (right < left) {
            path.add(")");
            backTracking(n, left, right + 1, path, res);
            path.removeLast();
        }
    }

    public static void main(String[] args) {
        GenerateParenthesis22 generateParenthesis22 = new GenerateParenthesis22();
        generateParenthesis22.generateParenthesis(3);
    }
}
